﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using ZhiJiao.Models.Entities;
using ZhiJiao.Service.Abstracts;
using ZhiJiao.Service.Dto;

namespace ZHIJIAO.Controllers
{
    public class HomeController : Controller
    {
        private readonly SignInManager<User> _signManager;
        private readonly UserManager<User> _userManager;
        private readonly IHomeService _homeService;
        private readonly ICurrentUser _currentUser;

        public HomeController(SignInManager<User> signInManager,
                              IHomeService homeService,
                              ICurrentUser currentUser)
        { 
            _signManager = signInManager;
            _userManager = signInManager.UserManager;
            _homeService = homeService;
            _currentUser = currentUser;
        }


        /// <summary>
        /// 主页视图
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public IActionResult Index()
        {
            ViewBag.Name = _currentUser.User.Name;
            ViewBag.InsName = _currentUser.User?.Instruction!=null? _currentUser.User?.Instruction.Name:"新创感统云平台";
            return View();
        }

        /// <summary>
        /// 获取用户模块
        /// </summary>
        /// <returns></returns>
        [HttpGet("api/home/get-user-modules")]
        public async Task<IActionResult> GetMudules()
        {
            return Json(await _homeService.GetUserModules());
        }


        /// <summary>
        /// 退出
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> Logout()
        {
            await _signManager.SignOutAsync();

            // 清空Session，因为可能会在Session中保存数据
            // Microsoft.AspNetCore.Session.Abandon();

            return RedirectToAction("Login", "Account");
        }
    }
}
